﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Shanbay.Core
{
    public class ShanbayUrl
    {
        public string Err = "";
        public string GetWordId(string token,string word)
        {
            if (string.IsNullOrEmpty(word))
            {
                Err = "单词为空";
                return "";
            }

            string strMsg = "";
            string url = String.Format("https://api.shanbay.com/bdc/search/?access_token={0}&word={1}", token, word);
            try
            {
                WebRequest request = WebRequest.Create(url);
                request.Method = "GET";
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("gb2312"));
                strMsg = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
                response.Close();
            }
            catch (Exception e)
            {
                Err = "获取单词Id错误\n"+ e.Message;
            }
            return strMsg;
        }
        public string PostWord(string token, string wordId)
        {
            string postUrl = String.Format("https://api.shanbay.com/bdc/learning/?access_token={0}", token);
            string ret = string.Empty;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes("id=" + wordId + ""); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                Err = "提交单词错误"+ ex.Message;
            }
            return ret;
        }
    }
}
